package com.sxf.controller.blog.admin;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

import com.sxf.common.tools.WPConstants;
import com.sxf.controller.SuperController;
import com.sxf.domain.viewbean.UserVO;
import com.sxf.formbean.UserForm;
import com.sxf.querybean.UserQuery;
import com.sxf.service.UserService;
import com.sxf.util.CookieUtils;
import com.sxf.util.PasswordUtils;
import com.sxf.util.SysLogUtil;

@Controller
@RequestMapping("/blog")
public class LoginController extends SuperController {

	@Resource
	private UserService us;
	@Resource(name = "memCacheManager")
	private CacheManager cm;

	/**
	 * <code>@ModelAttribute("user")</code>映射表单bean
	 * <p/>
	 * 如果view采用JSP的话<code>@ModelAttribute</code>
	 * 注解可以省略，但是如果是使用Velocity或FreeMarker 的话必须要加上，而且<code>@Valid</code>
	 * 注解和后面的BindingResult类型的参数之间不能有其他参数。
	 * 
	 * @param user
	 * @return
	 */

	@RequestMapping(value = "/login", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView doLogin(@Valid @ModelAttribute("loginForm") UserForm u,
			BindingResult br, Map<String, Object> model,
			@RequestParam(required = false) String tourl,
			NativeWebRequest request) throws Exception {

		ModelAndView mav = new ModelAndView();
		String url = "user/login";
		UserVO uv = (UserVO) request.getAttribute(WPConstants.LOGIN_USER,
				WebRequest.SCOPE_REQUEST);

		boolean isFirstLogin = false;
		if (u == null || (u.getLoginName() == null && u.getPassword() == null)) {
			isFirstLogin = true;
		}
		if (!isFirstLogin) {
			if (uv == null) {
				if (br.hasErrors()) {
					Map<String, Object> map = br.getModel();
					List<ObjectError> oe = br.getAllErrors();
					for (ObjectError oer : oe) {
						SysLogUtil.info(oer.getDefaultMessage());
					}
					for (Iterator<String> it = map.keySet().iterator(); it
							.hasNext();) {
						String key = it.next();
						SysLogUtil.debug("KEY:" + key + ",Value="
								+ map.get(key));

					}
					mav.addAllObjects(br.getModel());
				} else if (StringUtils.hasText(u.getLoginName())
						&& StringUtils.hasText(u.getPassword())) {
					UserQuery userQuery = new UserQuery();
					userQuery.setLoginName(u.getLoginName());

					String encodeStr = PasswordUtils.encode(u.getPassword(),
							u.getLoginName() + u.getPassword());
					userQuery.setPassword(encodeStr);
					List<UserVO> resultUser = us.queryList(userQuery);
					if (resultUser != null && !resultUser.isEmpty()) {
						UserVO user = resultUser.get(0);
						user.getUserMetaSet();
						mav.addObject(WPConstants.LOGIN_USER, user);
						dealUser(mav, request);
						url = "redirect:/blog/admin";
						// url = "/blog/admin";
					}
				}
			} else {
				url = "redirect:/blog/admin";
			}
			if (StringUtils.hasText(tourl)) {
				url = "redirect:" + tourl;
			}
		} else {
			isFirstLogin = true;
			url = "user/login";
		}
		mav.addObject(WPConstants.FIRST_LOGIN_FLAG, isFirstLogin);
		// return "redirect:/blog/login/show";
		mav.setViewName(url);
		return mav;
	}

	/**
	 * 保存用户信息
	 * 
	 * @param mav
	 * @param nr
	 */
	private void dealUser(ModelAndView mav, NativeWebRequest nr) {
		HttpServletRequest request = (HttpServletRequest) nr.getNativeRequest();
		HttpServletResponse response = (HttpServletResponse) nr
				.getNativeResponse();
		Object obj = mav.getModel().get(WPConstants.LOGIN_USER);
		if (obj != null && obj instanceof UserVO) {
			UserVO user = (UserVO) obj;
			String uuid = UUID.randomUUID().toString().replaceAll("[-]", "");
			cm.getCache(WPConstants.SESSION_CACHE).put(uuid, user);
			CookieUtils.addCookie(request, response, CookieUtils.USER_ID, uuid);
		}
	}

}
